package com.buu.manager.controller;

import com.alibaba.fastjson.JSON;
import com.buu.common.annotation.Log;
import com.buu.common.utils.DateUtils;
import com.buu.common.utils.PageUtils;
import com.buu.common.utils.Query;
import com.buu.common.utils.R;
import com.buu.education.domain.EducationEvaluateDO;
import com.buu.manager.domain.EduDO;
import com.buu.manager.domain.StudyProcessInfoDO;
import com.buu.manager.domain.StudyResourceDO;
import com.buu.manager.service.EduService;
import com.buu.manager.service.StudyProcessInfoService;
import com.buu.manager.service.StudyResourceService;
import com.buu.system.domain.SysUserDO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * 学习资料维护
 */
@RequestMapping("/study")
@Controller
public class StudyController {

    @Autowired
    private StudyResourceService studyResourceService;

    @Autowired
    private EduService eduService;

    @Autowired
    private StudyProcessInfoService studyProcessInfoService;

    @Value("${file.upload.path}")
    String path;

    @GetMapping("/manager")
    String study(Model model) {
        return "study/manager";
    }

    @GetMapping("/check")
    String check(Model model) {
        return "study/view";
    }

    @Log("上传视频")
    @GetMapping("/add")
    String add(Model model) {
        return "study/add";
    }

    @GetMapping("/list")
    @ResponseBody
    PageUtils list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);
        List<StudyResourceDO> eduList = studyResourceService.list(query);
        int total = studyResourceService.count(query);
        PageUtils pageUtil = new PageUtils(eduList, total);
        return pageUtil;
    }

    @ResponseBody
    @GetMapping("/view")
    StudyResourceDO view(@RequestParam("id") String id){
        return studyResourceService.get(Long.valueOf(id));
    }

    @Log("删除学习资料")
    @PostMapping("/remove")
    @ResponseBody
    Map<String, Object> remove(Long id) {
        Map<String, Object> rMap = new HashMap<>();

        StudyResourceDO studyResourceDO = studyResourceService.get(id);
        int result = studyResourceService.remove(id);
        rMap.put("success", result > 0);
        if(result > 0){
            //删除数据库记录后删除本地文件
            File file = new File(path, studyResourceDO.getFileName());
            boolean isDetele = false;
            if(file.exists()){
                isDetele = file.delete();
            }else{
                rMap.put("msg", "记录清除成功，文件不存在");
            }
            if(isDetele){  //删除成功，返回
                rMap.put("msg", "删除成功");
            }else{
                rMap.put("msg", "记录清除成功，删除失败");
            }
        }
        return rMap;
    }

    @PostMapping("/uploadResource")
    @ResponseBody
    R upload(@RequestParam("uploadFile") MultipartFile file, HttpServletRequest request){
        try{
            //获取参数
            String studyResourceName = request.getParameter("studyResrouceName");
            String unit = request.getParameter("unit");
            String sorted = request.getParameter("sorted");
            //获取文件名
            String fileName = file.getOriginalFilename();
            //获取文件后缀
            String suffix = fileName.substring(fileName.lastIndexOf(".")+1);

            //使用uuid为文件生成一个新的名字
            String newFileName = "ZY_" + System.currentTimeMillis()
                    + "." + suffix;

            //判断保存路径是否存在
            File targetFile = new File(path, newFileName);
            if(!targetFile.exists()){
                targetFile.getParentFile().mkdirs(); //创建目录
            }
            file.transferTo(targetFile);

            //保存记录至数据库
            StudyResourceDO studyResourceDO = new StudyResourceDO();
            studyResourceDO.setFileName(newFileName);
            studyResourceDO.setResourceName(studyResourceName);
            studyResourceDO.setSuffix(suffix);
            studyResourceDO.setUnit(unit);
            studyResourceDO.setSorted(sorted);

            if(studyResourceService.save(studyResourceDO) >0){
                return R.ok();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.error();
    }


    /**
     * 资源学习列表
     * @param params
     * @return
     */
    @GetMapping("/resource_list")
    @ResponseBody
    PageUtils resourceList(@RequestParam Map<String, Object> params) {
        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        SysUserDO sysUserDO = (SysUserDO) subject.getPrincipal();
        //根据用户获取身份
        EduDO eduDO = eduService.getUserBySysUserId(sysUserDO.getUserId());
        if("2".equals(eduDO.getType())){  //如果是学生，可以查看所在年级的视频
            params.put("unit", eduDO.getUnit());
        }
        // 查询列表数据
        Query query = new Query(params);
        List<StudyResourceDO> eduList = studyResourceService.list(query);
        int total = studyResourceService.count(query);
        PageUtils pageUtil = new PageUtils(eduList, total);
        return pageUtil;
    }

    /**
     * 获取学习的资源进度
     * @return
     */
    @GetMapping("/viewStudyResource")
    @ResponseBody
    StudyResourceDO viewStudyResource(@RequestParam("id") String id) {
        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        SysUserDO sysUserDO = (SysUserDO) subject.getPrincipal();
        //根据用户获取身份
        EduDO eduDO = eduService.getUserBySysUserId(sysUserDO.getUserId());
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        // 查询列表数据
        List<StudyResourceDO> eduList = studyResourceService.viewlist(params);
        return eduList != null ? eduList.get(0):null;
    }


    @ResponseBody
    @PostMapping("/savePlayTime")
    R savePlayTime(@RequestParam Map<String, Object> params) {
        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        SysUserDO sysUserDO = (SysUserDO) subject.getPrincipal();
        //根据用户获取身份
        EduDO eduDO = eduService.getUserBySysUserId(sysUserDO.getUserId());
        //查询是否已经有学习记录
        Map<String, Object> param = new HashMap<>();
        param.put("resourceId", params.get("id"));
        param.put("userId", eduDO.getId());
        StudyProcessInfoDO studyProcessInfoDO = studyProcessInfoService.get(param);
        if(studyProcessInfoDO != null){  //如果存在，更新
            studyProcessInfoDO.setStudyProcess(params.get("studyProcess").toString());
            int update = studyProcessInfoService.update(studyProcessInfoDO);
            if(update > 0){
                return R.ok();
            }
        }else{
            StudyProcessInfoDO spiDO = new StudyProcessInfoDO();
            spiDO.setResourceId(Long.valueOf(params.get("id").toString()));
            spiDO.setUserId(eduDO.getId());
            spiDO.setStudyProcess(params.get("studyProcess").toString());
            int insertResult = studyProcessInfoService.save(spiDO);
            if(insertResult > 0){
                return R.ok();
            }
        }


        return R.error();
    }

}
